package com.hsjk.szwj.module.train.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsjk.szwj.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.hsjk.szwj.framework.mybatis.core.query.QueryWrapperX;
import com.hsjk.szwj.framework.security.core.util.SecurityFrameworkUtils;
import com.hsjk.szwj.framework.tenant.core.aop.TenantIgnore;
import com.hsjk.szwj.module.member.api.user.MemberUserApi;
import com.hsjk.szwj.module.member.api.user.dto.MemberUserRespDTO;
import com.hsjk.szwj.module.train.controller.app.vo.fission.ClueSubmitReqVO;
import com.hsjk.szwj.module.train.controller.app.vo.fission.ClueSubmitRespVO;
import com.hsjk.szwj.module.train.controller.app.vo.fission.PerformanceDetailPageRespVO;
import com.hsjk.szwj.module.train.controller.app.vo.fission.PerformanceRespVO;
import com.hsjk.szwj.module.train.dal.dataobject.fission.EnrollClueDO;
import com.hsjk.szwj.module.train.dal.dataobject.order.CheckoutOrderDO;
import com.hsjk.szwj.module.train.dal.mysql.fission.IEnrollClueMapper;
import com.hsjk.szwj.module.train.dal.mysql.order.ICheckoutOrderMapper;
import com.hsjk.szwj.module.train.dal.mysql.product.IProductSkuMapper;
import com.hsjk.szwj.module.train.service.IFissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class FissionServiceImpl implements IFissionService {

    @Resource
    private IEnrollClueMapper enrollClueMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private ICheckoutOrderMapper checkoutOrderMapper;

    @Resource
    private IProductSkuMapper productSkuMapper;

    @Override
    public ClueSubmitRespVO submitClue(ClueSubmitReqVO clueSubmitReqVO) {
        ClueSubmitRespVO respVO = new ClueSubmitRespVO();

        // 按创建时间倒序获取最新的线索
        List<EnrollClueDO> enrollClueDOS = enrollClueMapper
                .selectList(new LambdaQueryWrapperX<EnrollClueDO>()
                        .eq(EnrollClueDO::getClientPhone, clueSubmitReqVO.getPhone())
                        .orderByDesc(EnrollClueDO::getCreateTime));

        // 是否已经提交过
        boolean submitted = enrollClueDOS.stream().anyMatch(enrollClueDO -> enrollClueDO.getMemberId().equals(SecurityFrameworkUtils.getLoginUserId()));
        if (submitted) {
            respVO.setIsSuccess(false);
            respVO.setFailReason("您已提交过线索");
            return respVO;
        }

        if (!enrollClueDOS.isEmpty()) {
            EnrollClueDO enrollClueDO = enrollClueDOS.get(0);

            // 如果学员id不为空，说明已经是学员了
            if (enrollClueDO.getStudentMemberId() != null) {
                respVO.setIsSuccess(false);
                respVO.setFailReason("该手机号已经是学员了");
                return respVO;
            }

            // 如果这条记录的创建时间加上有效天数大于当前时间，说明线索还有效
            int diff = enrollClueDO.getCreateTime().plusDays(enrollClueDO.getValidDays()).compareTo(LocalDateTime.now());
            if (diff > 0) {
                respVO.setIsSuccess(false);
                respVO.setFailReason("该用户已被上报线索且线索未过期");
                return respVO;
            }
        }

        // 保存线索
        EnrollClueDO enrollClueDO = new EnrollClueDO();
        enrollClueDO.setMemberId(SecurityFrameworkUtils.getLoginUserId());
        enrollClueDO.setClientName(clueSubmitReqVO.getName());
        enrollClueDO.setClientPhone(clueSubmitReqVO.getPhone());
        enrollClueDO.setClientAddress(clueSubmitReqVO.getAddress());
        enrollClueDO.setClientRemark(clueSubmitReqVO.getComment());
        enrollClueDO.setValidDays(30);

        int inserted = enrollClueMapper.insert(enrollClueDO);
        if (inserted > 0) {
            respVO.setIsSuccess(true);
            respVO.setFailReason(null);
        } else {
            respVO.setIsSuccess(false);
            respVO.setFailReason("提交失败，请联系管理员");
        }
        return respVO;
    }

    @Override
    public Page<EnrollClueDO> pageMyClue(Page<EnrollClueDO> page, String keyword) {
        return enrollClueMapper.selectPage(page, new LambdaQueryWrapperX<EnrollClueDO>()
                .eq(EnrollClueDO::getMemberId, SecurityFrameworkUtils.getLoginUserId())
                .and(i -> i
                        .like(EnrollClueDO::getClientName, keyword)
                        .or()
                        .like(EnrollClueDO::getClientPhone, keyword))
                .orderByDesc(EnrollClueDO::getCreateTime));
    }

    @Override
    public List<MemberUserRespDTO> listMyInvitedUsers(String keyword) {
        return memberUserApi.getInvitedUserList(SecurityFrameworkUtils.getLoginUserId(), keyword);
    }

    @Override
    @TenantIgnore
    public PerformanceRespVO getMyPerformance() {
        Integer totalInvite = memberUserApi.getInvitedUserCount(SecurityFrameworkUtils.getLoginUserId());
        List<CheckoutOrderDO> checkoutOrderDOS = checkoutOrderMapper.selectList(new LambdaQueryWrapperX<CheckoutOrderDO>()
                .eq(CheckoutOrderDO::getMemberId, SecurityFrameworkUtils.getLoginUserId()));
        Long totalReward = checkoutOrderDOS.stream().mapToLong(CheckoutOrderDO::getCheckoutAmount).sum();
        return new PerformanceRespVO().setTotalInvite(totalInvite).setTotalReward(totalReward);
    }

    @Override
    public PerformanceDetailPageRespVO getMyPerformanceDetail(Page<PerformanceDetailPageRespVO> page, Integer status, Integer type) {
        List<CheckoutOrderDO> checkoutOrderDOS = checkoutOrderMapper.selectList(new LambdaQueryWrapperX<CheckoutOrderDO>()
                .eq(CheckoutOrderDO::getMemberId, SecurityFrameworkUtils.getLoginUserId()));

        return null;
    }
}
